package com.sunda.spmsweb.ordercontroller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.entity.vo.OrderWorkshopQueryVo;
import com.sunda.spmsorder.service.IOrderLogService;
import com.sunda.spmsorder.service.IOrderWorkshopDtlService;
import com.sunda.spmsorder.service.IOrderWorkshopService;
import com.sunda.spmsweb.oaservice.OaService;
import com.sunda.spmsweb.util.JWTUtil;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 车间请购单 前端控制器
 * </p>
 *
 * @author Wayne
 * @since 2021-02-02
 */
@RestController
@RequestMapping("/orderWorkshop")
@Api(tags = "车间请购单接口", description = "车间请购订单接口")
public class OrderWorkshopController {

    @Autowired
    IOrderWorkshopService iOrderWorkshopService;

    @Autowired
    IOrderWorkshopDtlService iOrderWorkshopDtlService;

    @Autowired
    IOrderLogService iOrderLogService;

    @RequestMapping("/getOrderWs")
    @ApiOperation(value = "获取车间请购单信息（表头 分页）", notes = "获取车间请购单信息\n" +
            "示例 用户工号必输：userId = 20001\n" +
            "可选字段-订单状态：orderStatus = 1，传空则默认查询所有状态。查看同工厂同车间下所有请购单。", httpMethod = "POST")
    public ResponseResult getOrderWS(@RequestParam(required = false) String userId,
                                     @RequestParam(required = false) String orderStatus,
                                     @RequestParam(defaultValue = "1") int pageNo,
                                     @RequestParam(defaultValue = "20") int pageSize,
                                     @RequestParam(required = false) String applicationDateStart,
                                     @RequestParam(required = false) String applicationDateEnd,
                                     @RequestParam(required = false) String urgencyDegree,
                                     @RequestParam(required = false) String spmsWsId,
                                     @RequestParam(required = false) String authorId,
                                     @RequestParam(required = false) String userName) {
        try {
            if (StringUtils.isEmpty(userId)){
                userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            }
            return ResponseResult.success().add("orderWorkshop", iOrderWorkshopService.getOrderWS(userId, orderStatus, pageNo, pageSize, applicationDateStart, applicationDateEnd, urgencyDegree, spmsWsId,authorId, userName));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getOrderWs1")
    @ApiOperation(value = "获取车间请购单信息（表头 分页）", notes = "获取车间请购单信息\n" +
            "示例 用户工号必输：userId = 20001\n" +
            "可选字段-订单状态：orderStatus = 1，传空则默认查询所有状态。查看同工厂同车间下所有请购单。", httpMethod = "POST")
    public ResponseResult getOrderWS1(@RequestBody OrderWorkshopQueryVo orderWorkshopQueryVo) {
        try {
            return ResponseResult.success().add("orderWorkshop", iOrderWorkshopService.getOrderWS1(orderWorkshopQueryVo));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getOrderWsDtl")
    @ApiOperation(value = "获取车间请购单详情（行项目 一个单）", notes = "获取一个车间请购单详情信息\n" +
            "示例 车间请购单号必输：spmsWsId = GH011002-20210204-0001\n" +
            "返回车间请购单详情，请购单行项目物料关联全部长协信息，车间请购单日志信息。", httpMethod = "POST")
    public ResponseResult getOrderWsDtl(String spmsWsId) {
        try {
            return ResponseResult.success()
                    .add("orderWorkshopDtl", iOrderWorkshopDtlService.getOrderWsDtl(spmsWsId))
                    .add("orderLogList", iOrderLogService.orderLogList(spmsWsId));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getOrderWsDtlWithInventory")
    @ApiOperation(value = "获取车间请购单详情(含在库、在途、安全库存)", notes = "获取车间请购单详情(含在库、在途、安全库存)\n" +
            "示例 车间请购单号必输：spmsWsId = GF31-EL-20210825-001, GF31-EL-20210811-001\n" +
            "返回车间请购单详情，请购单行项目物料关联全部长协信息，车间请购单日志信息。", httpMethod = "POST")
    public ResponseResult getOrderWsDtlWithInventory(String spmsWsId) {
        try {
            return ResponseResult.success()
                    .add("orderWorkshopDtl", iOrderWorkshopDtlService.getOrderWsDtlWithInventory(spmsWsId))
                    .add("orderLogList", iOrderLogService.orderLogList(spmsWsId));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getOrderWsDtls")
    @ApiOperation(value = "获取车间请购单详情（行项目 多个单）", notes = "获取多个车间请购单详情信息，用于机电主任合单审批。\n" +
            "示例请求参数：\n" +
            "{\n" +
            "\t\"spmsWsIds\": [\"GH011002-20210203-0004\", \"GH011002-20210203-0005\"]\n" +
            "}\n" +
            "返回车间请购单详情，不包括车间请购单日志信息。", httpMethod = "POST")
    public ResponseResult getOrderWsDtls(@RequestBody JSONObject jsonObject) {
        try {
            return ResponseResult.success()
                    .add("orderWorkshopDtl", iOrderWorkshopDtlService.getOrderWsDtls(jsonObject));
        } catch (Exception e) {
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getOrderWsDtlList")
    @ApiOperation(value = "获取多个车间请购单详情(含在库、在途、安全库存)", notes = "获取多个车间请购单详情(含在库、在途、安全库存)，用于机电主任合单审批。\n" +
            "获取多个车间请购单明细信息，包含 在库库存、在途库存、安全库存等信息；\n" +
            "示例请求参数：\n" +
            "{\n" +
            "\t\"spmsWsIds\": [\"GH011002-20210203-0004\", \"GH011002-20210203-0005\"]\n" +
            "}\n" +
            "返回车间请购单详情，不包括车间请购单日志信息。", httpMethod = "POST")
    public ResponseResult getOrderWsDtlList(@RequestBody JSONObject jsonObject) {
        try {
            return ResponseResult.success()
                    .add("orderWorkshopDtl", iOrderWorkshopDtlService.getOrderWsDtlList(jsonObject));
        } catch (Exception e) {
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/addOrderWorkshop")
    @ApiOperation(value = "新建车间请购单及详情", notes = "新建车间请购单及详情\n" +
            "表头字段 status: 车间请购单SPMS状态（0已删除；1车间主任创建可修改；2车间已提交不可改；3机电主任审批不通过；4机电主任审批通过提交OA；5OA审批通过；6提交SRM；）\n" +
            "uuid 为Java生成用于车间请购单表头和行项目关联的标记；表头车间单号由数据库按规则自动生成；行项目车间单号由行项目新建时通过uuid关联从表头获取；\n" +
            "车间请购单号 GH011002-20210202-0001 生成规则：工厂代码 + 车间代码 + 创建人当地系统日期（createDate） + 序列号；" +
            "createDate格式前端传给后端为 yyyy-mm-dd；单号生成日期中横线由数据库自动去除；\n" +
            "orderWorkshopDtl.brand: 取自 srm 长协信息中的 brand；\n" +
            "{\n" +
            "\t\"orderWorkshop\": {\n" +
            "\t\t\"userId\": \"20001\",\n" +
            "\t\t\"lastName\": \"20001\",\n" +
            "\t\t\"subject\": \"GF011002-20210201-车间请购单\",\n" +
            "\t\t\"projectType\": \"1\",\n" +
            "\t\t\"werks\": \"GH01\",\n" +
            "\t\t\"workshopCode\": \"1002\",\n" +
            "\t\t\"projectStatus\": \"1\",\n" +
            "\t\t\"dateRequired\": \"2021-05-01\",\n" +
            "\t\t\"urgency\": \"2\",\n" +
            "\t\t\"projectCode\": \"\",\n" +
            "\t\t\"justification\": \"申请原因\",\n" +
            "\t\t\"applicationDate\": \"2021-02-10\",\n" +
            "\t\t\"status\": \"1\",\n" +
            "\t\t\"createDate\": \"2021-02-02\",\n" +
            "\t\t\"purchaseLocation\": \"0\"\n" +
            "\t},\n" +
            "\t\"orderWorkshopDtl\": [{\n" +
            "\t\t\t\"rowId\": 10,\n" +
            "\t\t\t\"materialNo\": \"130011853\",\n" +
            "\t\t\t\"materialZhDesc\": \"马克杯 端底白瓷花13 普通包装 48PCS/CTN\",\n" +
            "\t\t\t\"materialEnDesc\": \"MUG\",\n" +
            "\t\t\t\"requestQty\": 4,\n" +
            "\t\t\t\"approvalQty\": 4,\n" +
            "\t\t\t\"basicUnit\": \"PCS\",\n" +
            "\t\t\t\"brand\": \"\",\n" +
            "\t\t\t\"rowStatus\": \"\",\n" +
            "\t\t\t\"rowComment\": \"\",\n" +
            "\t\t\t\"deviceId\": \"\",\n" +
            "\t\t\t\"deviceCategory\": \"\",\n" +
            "\t\t\t\"deviceType\": \"\",\n" +
            "\t\t\t\"materialCategory\": \"\",\n" +
            "\t\t\t\"longContractCode\": \"\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"rowId\": 20,\n" +
            "\t\t\t\"materialNo\": \"130011854\",\n" +
            "\t\t\t\"materialZhDesc\": \"马克杯 端底白瓷花14 普通包装 48PCS/CTN\",\n" +
            "\t\t\t\"materialEnDesc\": \"MUG\",\n" +
            "\t\t\t\"requestQty\": 5,\n" +
            "\t\t\t\"approvalQty\": 5,\n" +
            "\t\t\t\"basicUnit\": \"PCS\",\n" +
            "\t\t\t\"brand\": \"\",\n" +
            "\t\t\t\"rowStatus\": \"\",\n" +
            "\t\t\t\"rowComment\": \"\",\n" +
            "\t\t\t\"deviceId\": \"\",\n" +
            "\t\t\t\"deviceCategory\": \"\",\n" +
            "\t\t\t\"deviceType\": \"\",\n" +
            "\t\t\t\"materialCategory\": \"\",\n" +
            "\t\t\t\"longContractCode\": \"\"\n" +
            "\t\t}\n" +
            "\t]\n" +
            "}", httpMethod = "POST")
    public ResponseResult addOrderWorkshop(@RequestBody JSONObject jsonObject) {
        try {
            return iOrderWorkshopService.addOrderWorkshop(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/updateOrderWorkshop")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "更新车间请购单（表头）", notes = "更新车间请购单表头\n" +
            "示例请求json对象数据，唯一性字段 uuid，请求体至少包含以下字段：\n" +
            "{\n" +
            "\t\"orderWorkshop\": {\n" +
            "\t\t\"uuid\": \"6013cbd70b6d47debeaa83a77f23657a\",\n" +
            "\t\t\"spmsWsId\": \"GH011002-20210203-0005\",\n" +
            "\t\t\"subject\": \"GF011002-20210201-车间请购单\",\n" +
            "\t\t\"userId\": \"20001\",\n" +
            "\t\t\"projectType\": \"1\",\n" +
            "\t\t\"projectStatus\": \"1\",\n" +
            "\t\t\"dateRequired\": \"2021-05-01\",\n" +
            "\t\t\"urgency\": \"2\",\n" +
            "\t\t\"projectCode\": null,\n" +
            "\t\t\"workshopCode\": \"1002\",\n" +
            "\t\t\"justification\": \"申请原因\",\n" +
            "\t\t\"status\": \"1\",\n" +
            "\t\t\"purchaseLocation\": \"0\"\n" +
            "\t}\n" +
            "}", httpMethod = "POST")
    public ResponseResult updateOrderWorkshop(@RequestBody JSONObject jsonObject) {
        try {
            return iOrderWorkshopService.updateOrderWorkshop(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }


    @RequestMapping("/updateOrderWorkshopDtl")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "更新车间请购单（行项目）", notes = "更新车间请购单行项目，更新规则：整体详情删除重建详情数据\n" +
            "示例请求json对象数据，唯一性字段 uuid，请求体至少包含以下字段：\n" +
            "{\n" +
            "\t\"uuid\": \"6013cbd70b6d47debeaa83a77f23657a\",\n" +
            "\t\"spmsWsId\": \"GH011002-20210203-0005\",\n" +
            "\t\"userId\": \"20001\",\n" +
            "\t\"orderWorkshopDtl\": [{\n" +
            "\t\t\"rowId\": 10,\n" +
            "\t\t\"materialNo\": \"130011853\",\n" +
            "\t\t\"materialZhDesc\": \"马克杯 端底白瓷花13 普通包装 48PCS/CTN\",\n" +
            "\t\t\"materialEnDesc\": \"MUG\",\n" +
            "\t\t\"requestQty\": 4,\n" +
            "\t\t\"approvalQty\": 4,\n" +
            "\t\t\"basicUnit\": \"PCS\",\n" +
            "\t\t\"brand\": \"\",\n" +
            "\t\t\"rowStatus\": \"\",\n" +
            "\t\t\"rowComment\": \"\",\n" +
            "\t\t\"deviceId\": \"\",\n" +
            "\t\t\"deviceCategory\": \"\",\n" +
            "\t\t\"deviceType\": \"\",\n" +
            "\t\t\"materialCategory\": \"\",\n" +
            "\t\t\"longContractCode\": \"\"\n" +
            "\t}]\n" +
            "}", httpMethod = "POST")
    public ResponseResult updateOrderWorkshopDtl(@RequestBody JSONObject jsonObject) {
        try {
            return iOrderWorkshopDtlService.updateOrderWorkshopDtl(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getOrderWSList")
    @ApiOperation(value = "获取待审批提交的车间请购单及详情", notes = "获取当前用户所属工厂下各车间提交到机电主任的待审批车间请购单，及行项目信息。" +
            "前端需控制此接口仅机电主任可访问。", httpMethod = "POST")
    public ResponseResult getOrderWSList(@RequestParam(defaultValue = "1") int pageNo,
                                         @RequestParam(defaultValue = "20") int pageSize) {
        try {
            String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            /** 已保存待提交的状态 = 2 */
            String orderStatus = "2";
            return ResponseResult.success().add("orderWorkshop", iOrderWorkshopService.getOrderWSList(userId, orderStatus, pageNo, pageSize));
        } catch (Exception e) {
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getOrderLogWByUuid")
    @ApiOperation(value = "根据车间请购单uuid查询工厂单日志", notes = "根据车间请购单UUID查询对应工厂请购单SPMS日志信息，" +
            "示例 ：uuid = 788e02c58f1b426991932616433f285f", httpMethod = "POST")
    public ResponseResult getOrderLogWByUuid(String orderWorkshopUuid) {
        try {
            return ResponseResult.success().add("orderWerksLog", iOrderWorkshopService.getOrderLogWByUuid(orderWorkshopUuid));
        } catch (Exception e) {
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getOrderLogOaByUuid")
    @ApiOperation(value = "根据车间请购单uuid查询OA日志", notes = "根据车间请购单UUID查询对应工厂请购单OA日志信息，" +
            "示例 ：uuid = 788e02c58f1b426991932616433f285f", httpMethod = "POST")
    public ResponseResult getOrderLogOaByUuid(String orderWorkshopUuid) {
        try {
            String oaBianhao = iOrderWorkshopService.getOrderLogOaByUuid(orderWorkshopUuid);
            System.out.println("oaBianhao ====== " + oaBianhao);
            if (oaBianhao == null || oaBianhao.length() == 0) {
                return ResponseResult.error();
            }
            OaService oaService = new OaService();
            return ResponseResult.success().add("orderWerksOALog", oaService.getOALog(oaBianhao));
        } catch (Exception e) {
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }
}
